//
//  BFAutoBackgroundView.m
//  13KModel
//
//  Created by ISS on 21/09/12.
//
//
// CLASS INCLUDES
#import "BFAutoBackgroundView.h"

// SYSTEM INCLUDES

// CONST DEFINE
CGFloat const kMaskAlphaValue = .2f;

@interface BFAutoBackgroundView(){
    UIImageView *imageView;
    UIView      *maskView;
    
    NSInteger   curIndex;
}

- (NSInteger)newCanvasIndex;
- (BOOL)checkIndexValid:(NSInteger)index;
@end

@implementation BFAutoBackgroundView
@synthesize imageArray = _imageArray;
@synthesize isMaskSupported = _isMaskSupported;

- (id)initWithFrame:(CGRect)frame
{
    self = [super initWithFrame:frame];
    if (self) {
        self.isMaskSupported = NO;
        self.clipsToBounds = YES;
    }
    return self;
}

#pragma mark- setter

- (void)setImageArray:(NSArray *)imageArray
{
    _imageArray = imageArray;
    
    if (_imageArray) {
        
        if (!imageView) {
            imageView = [[UIImageView alloc] initWithFrame:self.bounds];
            imageView.autoresizingMask = UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleHeight;
            imageView.backgroundColor = [UIColor blackColor];
            imageView.contentMode = UIViewContentModeScaleAspectFill;
            if (maskView) {
                [self insertSubview:imageView belowSubview:maskView];
            }
        }
        [self updateBackground:NO];
    }
}

- (void)setIsMaskSupported:(BOOL)isMaskSupported
{
    if (isMaskSupported && !maskView) {
        maskView = [[UIView alloc] initWithFrame:self.bounds];
        maskView.backgroundColor = [UIColor blackColor];
        maskView.alpha = kMaskAlphaValue;
        maskView.autoresizingMask = UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleHeight;
        
        [self addSubview:maskView];
    }
    
    _isMaskSupported = isMaskSupported;    
}

#pragma mark - private methods
- (NSInteger)newCanvasIndex
{
    if (!self.imageArray || self.imageArray.count == 0) {
        return -1;
    }
    
    NSInteger randomIndex = -1;
    while ((randomIndex = arc4random()%self.imageArray.count) == curIndex) {
    }
    
    return randomIndex;
}

- (BOOL)checkIndexValid:(NSInteger)index
{
    if (!self.imageArray) {
        return NO;
    }
    
    return !(index<0 || index>=self.imageArray.count);
}

#pragma mark - public methods

- (void)updateBackground:(BOOL)animation
{
    curIndex = [self newCanvasIndex];
    
    if (animation) {
        [UIView animateWithDuration:2.0f animations:^{
            imageView.alpha = 0.1;
        } completion:^(BOOL finished) {
            imageView.image = [UIImage imageNamed:[self.imageArray objectAtIndex:curIndex]];
            [UIView animateWithDuration:2.0f animations:^{
                imageView.alpha = 1.0f;
            }];
        }];
    }
    else{
        imageView.image = [UIImage imageNamed:[self.imageArray objectAtIndex:curIndex]];
    }
}


@end
